package com.cheetah.start.system.mail.service;


import com.cheetah.start.system.mail.domain.MailDo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件服务
 *
 * @author Feel
 * @date 2021/08/19
 */
@Slf4j
@Service
public class MailService {

    /** 发件人地址 */
    @Value("${spring.mail.username}")
    private String fromMailAddress;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送邮件
     *
     * @param mailDo 邮件
     * @throws MessagingException 通讯异常
     */
    public void sendMail(MailDo mailDo) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromMailAddress);
        helper.setTo(mailDo.getTo());
        helper.setSubject(mailDo.getTitle());
        helper.setText(mailDo.getContent(), mailDo.isHtml());
        mailSender.send(message);
    }
}
